﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="VirtualMarketProvider.GTC.cs" company="">
//   
// </copyright>
// <summary>
//   The virtual market provider.
// </summary>
// --------------------------------------------------------------------------------------------------------------------


using System;
using Systemathics.FrameWork;

namespace Systemathics.Providers
{
    /// <summary>
    /// The virtual market provider.
    /// </summary>
    public sealed partial class VirtualMarketProvider
    {
        private bool LimitOrderManager(ref OrderTracker o)
        {
            lock (o)
            {
                //var delay = Time.Now - o.SendTime;
                var lasttime = LastFeeds[o.InstrumentId].Blotter[QuoteLevel.One].Time;
                var delay =  lasttime - o.SendTime;
                if (delay.TotalMilliseconds > VMParameters.AckDelay)
                {
                    if (o.isPending && !o.isCancelling && !o.isModifying  && !o.isCancelled)
                    {
                        o.SetisAcknoweldged(true);
                        _EmitOrderStatus(this, new OrderStatusEventArgs(o.Id, OrderStatus.ACK, o.TargetQuantity, o.TargetPrice, o.RemainingQuantity, 0, null) { SendTime = o.SendTime, AckTime = lasttime });
                        return CheckIfLimitExecution(ref o);
                    }
                    if (!o.isPending && !o.isCancelling && !o.isModifying)
                    {
                        // Despite !o.isCancelling && !o.isModifying are included in !ispending we need them cause its an || condition in isPending and not && !!!
                        return CheckIfLimitExecution(ref o);
                    }
                    if (o.isCancelling)
                    {
                        o.SetisCancelling(false);
                        o.SetisCancelled(true);
                        if (o.RemainingQuantity > 0)
                        {
                            _EmitOrderStatus(this, new OrderStatusEventArgs(o.Id, OrderStatus.ACK_CANCEL, o.TargetQuantity, o.TargetPrice, 0, o.RemainingQuantity, null) { CancelTime = o.CancelTime, CancelAckTime = lasttime });
                            return true;
                        }
                    }
                    else if (o.isModifying)
                    {
                        o.SetisModifying(false);
                        o.SetisModified(true);
                        _EmitOrderStatus(this, new OrderStatusEventArgs(o.Id, OrderStatus.ACK_MODIFY, o.TargetQuantity, o.TargetPrice, o.RemainingQuantity, 0, null) {ModifyTime = o.ModifyTime, ModifyAckTime = lasttime });
                    }
                }
                return false;
            }
        }
    }
}
